import * as rp from 'request-promise';
import * as crypto from 'crypto';
import { UserInfoVo } from "./UserInfoVo";
import * as url from 'url';
import * as moment from 'moment';
import env from './../../../config/env';
export class DTalkApiUtil {

    corpid: string = env.corpId;//"dingdbc25f3af83b934435c2f4657eb6378f";//fuxing
    corpsecret: string = env.corpsecret;//'bZN2ppXzXv6uXE7gK4zgizVb_do2ndHLBHT6KvsacUi_EqvJbvXo6E2WwSfznd0t'; //CorpSecret：xTnUH-9iXWX6aLGC6bWFsvByr8zIUeiG6CyNZL6L4OiofpxHvI_gaCVjNpvYiTfC
    private oapiHost = 'https://oapi.dingtalk.com';
    url: string = 'https://open.dingtalk.com';
    ticket: string;
    expires: number;
    access_token: string;
    expires_token: number;
    async getAccessToken() {
        if (!this.expires_token || this.expires_token < Date.now() + 20 * 60 * 100) {//提前20分钟获取 access_token

            console.log("getAccessToken 向钉钉服务器获取 accessToken gj");


            let rt = await rp.get(`https://oapi.dingtalk.com/gettoken?corpid=${this.corpid}&corpsecret=${this.corpsecret}`, { json: true })


            if (rt.errcode === 0) {
                //           {
                //     "access_token": "xxxxxx",
                //     "expires_in": 7200
                // }
                this.access_token = rt.access_token;
                this.expires_token = Date.now() + 7200 * 1000;
                // await authCorp.save();
                return rt.access_token;
            } else {
                console.log('error.....', rt);

                // log4js.getLogger('log_error').error(rt);
            }
        } else {

            return this.access_token;
        }

        return await rp.get(`https://oapi.dingtalk.com/gettoken?corpid=${this.corpid}&corpsecret=${this.corpsecret}`, { json: true })

    }

    async getJsapi_ticket() {

        let accessToken = await this.getAccessToken();
        console.log('------------------accessToken', accessToken);
        if (!this.expires || this.expires < Date.now() + 20 * 60 * 1000) {//ticket 超时，重新获取
            let json = await rp.get(`https://oapi.dingtalk.com/get_jsapi_ticket?access_token=${accessToken}`, { json: true })
            console.log(json)
            if (json.errcode === 0) {
                this.ticket = json.ticket;
                this.expires = Date.now() + 7200 * 1000;
                // await corp.save();
                return this.ticket;
            } else {
                console.log("getJsApiTicket", json);
                // log4js.getLogger('log_error').error(json);
                return null;
            }
        } else {
            console.log("tick 未超时", this.ticket);

            return this.ticket;
        }

        // let data = await this.getAccessToken();
        // let rt = await rp.get(`https://oapi.dingtalk.com/get_jsapi_ticket?access_token=${data.access_token}`, { json: true })

    }

    async getSign(nonceStr: string, timeStamp: number, origUrl: string) {

        let ticket = await this.getJsapi_ticket();
        //   corp.expires
        var origUrlObj = url.parse(origUrl);
        delete origUrlObj['hash'];
        var newUrl = url.format(origUrlObj);
        var plain = 'jsapi_ticket=' + ticket +
            '&noncestr=' + nonceStr +
            '&timestamp=' + timeStamp +
            '&url=' + newUrl;

        console.log(plain);
        var sha1 = crypto.createHash('sha1');
        sha1.update(plain, 'utf8');
        var signature = sha1.digest('hex');
        return signature;

    }

    async getUserInfo(code: string): Promise<UserInfoVo> {
        let accessToken = await this.getAccessToken();

        let json = await rp.get(`https://oapi.dingtalk.com/user/getuserinfo?access_token=${accessToken}&code=${code}`, { json: true });
        //if (json.errcode === 0) {
            return json as UserInfoVo;
        //} else {
            //console.log("getUserInfo", json);
            //return UserInfoVo;//免登失败
        //}
    }

    async getUser_Info(userId: string) {
        let ACCESS_TOKEN = await this.getAccessToken();
        //https://oapi.dingtalk.com/user/get?access_token=ACCESS_TOKEN&userid=zhangsan
        let json = await rp.get(`https://oapi.dingtalk.com/user/get?access_token=${ACCESS_TOKEN}&userid=${userId}`, { json: true });

        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }


    }

    async getWorkDate(userId: String, workDateFrom: String, workDateTo: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        // https://oapi.dingtalk.com/attendance/list?access_token=ACCESS_TOKEN

        let json = await rp.post(`https://oapi.dingtalk.com/attendance/list?access_token=${ACCESS_TOKEN}`, {

            body: {
                userId: userId,//非必填
                workDateFrom: workDateFrom,
                workDateTo: workDateTo
            }
            , json: true
        });
        return json;



    }
    async getWork_Date(workDateFrom: String, workDateTo: String) {
        let ACCESS_TOKEN = await this.getAccessToken();
        // https://oapi.dingtalk.com/attendance/list?access_token=ACCESS_TOKEN

        let json = await rp.post(`https://oapi.dingtalk.com/attendance/list?access_token=${ACCESS_TOKEN}`, {

            body: {

                workDateFrom: workDateFrom,
                workDateTo: workDateTo
            }
            , json: true
        });
        return json;

    }

    async listRecord(LR: any) {
        //https://oapi.dingtalk.com/attendance/listRecord?access_token=ACCESS_TOKEN
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.post(`https://oapi.dingtalk.com/attendance/listRecord?access_token=${ACCESS_TOKEN}`,
            {
                body: LR, json: true
            });
        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }
    }

    async emplList(deptId: number, size: number = 100, offset: number = 0) {
        //https://oapi.dingtalk.com/user/list?access_token=ACCESS_TOKEN&department_id=1
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/list?access_token=${ACCESS_TOKEN}&department_id=${deptId}&offset=${offset}&size=${size}`, { json: true });
        console.log(ACCESS_TOKEN, deptId, offset, size);
        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }

    }

    async sendMsg(OA: any) {
        //https://oapi.dingtalk.com/message/send?access_token=ACCESS_TOKEN
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.post(`https://oapi.dingtalk.com/message/send?access_token=${ACCESS_TOKEN}`,
            {
                body: OA, json: true
            });
        if (json.errcode === 0) {
            return json;
        } else {
            throw json.errmsg;
        }
    }
    async deptList() {
        //https://oapi.dingtalk.com/department/list?access_token=ACCESS_TOKEN
        let ACCESS_TOKEN = await this.getAccessToken();
        let json: any = await rp.get(this.oapiHost + '/department/list?access_token=' + ACCESS_TOKEN, { json: true });
        if (json.errcode === 0) {
            return json.department;
        } else {
            throw json.errmsg;
        }
    }

    /**
     * 
     * 部门信息
     */
    async getDept_Info(id: number) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}&id=${id}`, { json: true });

        if (json.errcode === 0) {
            return json;
        } else {
            return json.errmsg;
        }
    }

    /**
     * 
     * 部门人员
     */
    async getDept_User(id: number) {
        let ACCESS_TOKEN = await this.getAccessToken();
        let json = await rp.get(`https://oapi.dingtalk.com/user/simplelist?access_token=${ACCESS_TOKEN}&department_id=${id}`, { json: true });

        if (json.errcode === 0) {
            return json;
        } else {
            return json.errmsg;
        }
    }
}

let dTalkApiUtil = new DTalkApiUtil();

export default dTalkApiUtil;